﻿from hachoir_core.stream import *
from hachoir_core.field import *
import logging

logging.basicConfig(level=0, format="%(message)s")

project = ur"D:\작업장\FaToolBox\gxtools\xxxx\Resource\Others"

stream = FileInputStream(project + ur"\COMMENT.wcd")

class HeaderItem(FieldSet):
    def createFields(self):
        yield UInt8(self, "length")
        if self["length"].value != 0xff:
            code = UInt8(self, "code")
            self._name = "{0}[{1}]".format(self.name, code.display)
            yield code
            yield String(self, "value", self["length"].value - 2)

class Header(FieldSet):
    def createFields(self):
        yield UInt16(self, "length")
        while True:
            item = HeaderItem(self, "item")
            if item["length"].value == 0xff:
                break;
            yield item
        dummyCount = self["length"].value - self.current_size / 8
        yield PaddingBytes(self, "dummy", dummyCount)
        
    def title(self):
        return self["item[1]"]
        
class Index(FieldSet):
    def createFields(self):
        class DeviceItem(FieldSet):
            def createFields(self):
                yield UInt8(self, "code")
                yield UInt8(self, "extCode")
                yield UInt32(self, "start")
                yield UInt32(self, "count")
                
        yield UInt32(self, "length")
        yield PaddingBytes(self, "unknown", 2)
        yield UInt8(self, "commentSize")
        yield UInt8(self, "aliasSize")
        count = UInt16(self, "count")
        yield count

        self._devCount = 0
        for i in range(count.value):
            devItem = DeviceItem(self, "item[]")
            self._devCount += devItem["count"].value
            yield devItem
        assert self["length"].value == self.current_size / 8
        
    def getCommentItemClass(self):
        class CommentItem(FieldSet):
            def createFields(_self):
                yield String(_self, "alias", self["aliasSize"].value)
                yield String(_self, "comment", self["commentSize"].value)
        return CommentItem

class CommentFile(Parser):
    endian = LITTLE_ENDIAN
    def createFields(self):
        yield Header(self, "header")
        index = Index(self, "index")
        yield index
        for i in range(index["count"].value):
            device = index["item[{0}]".format(i)]
            #print device, device["count"].value
        CommentItem = index.getCommentItemClass()
        for i in range(index._devCount):
            yield CommentItem(self, "comment[]")
        
comment = CommentFile(stream)
comment._feedAll()
print comment["/comment[0]/comment"]
print comment["/comment[1]/comment"]
print comment["/comment[2]/comment"]
